import random
import five_black_detect

# 定义棋盘大小和玩家符号
ROWS, COLS = 3, 3
PLAYER_X = 'X'  # 玩家
PLAYER_O = 'O'  # 电脑AI
EMPTY = ' '

# 函数：打印棋盘
def print_board(board):
    for row in board:
        print(" | ".join(row))
        print("-" * 9)

# 函数：检查当前状态是否是结束状态（胜负或平局）
def check_game_over(board):
    # 检查行和列
    for i in range(ROWS):
        if board[i][0] == board[i][1] == board[i][2] != EMPTY:  # 检查行
            return board[i][0]
        if board[0][i] == board[1][i] == board[2][i] != EMPTY:  # 检查列
            return board[0][i]

    # 检查对角线
    if board[0][0] == board[1][1] == board[2][2] != EMPTY:  # 主对角线
        return board[0][0]
    if board[0][2] == board[1][1] == board[2][0] != EMPTY:  # 副对角线
        return board[0][2]

    # 检查是否平局
    if all(board[i][j] != EMPTY for i in range(ROWS) for j in range(COLS)):
        return "Draw"

    # 游戏未结束
    return None

# 函数：实现Minimax算法来找到最优的下棋位置
def minimax(board, depth, is_maximizing):
    result = check_game_over(board)

    if result == PLAYER_X:
        return -1  # X赢了
    elif result == PLAYER_O:
        return 1  # O赢了
    elif result == "Draw":
        return 0  # 平局

    if is_maximizing:
        best_score = -float('inf')
        for i in range(ROWS):
            for j in range(COLS):
                if board[i][j] == EMPTY:
                    board[i][j] = PLAYER_O
                    score = minimax(board, depth + 1, False)
                    board[i][j] = EMPTY
                    best_score = max(score, best_score)
        return best_score
    else:
        best_score = float('inf')
        for i in range(ROWS):
            for j in range(COLS):
                if board[i][j] == EMPTY:
                    board[i][j] = PLAYER_X
                    score = minimax(board, depth + 1, True)
                    board[i][j] = EMPTY
                    best_score = min(score, best_score)
        return best_score

# 函数：让电脑选择最优的下棋位置
def computer_move(board):
    best_move = None
    best_score = -float('inf')
    for i in range(ROWS):
        for j in range(COLS):
            if board[i][j] == EMPTY:
                board[i][j] = PLAYER_O
                score = minimax(board, 0, False)
                board[i][j] = EMPTY
                if score > best_score:
                    best_score = score
                    best_move = (i, j)

    if best_move:
        board[best_move[0]][best_move[1]] = PLAYER_O
        return best_move  # 返回AI选择的坐标

# 函数：处理玩家输入
def get_player_move(board,get_row,get_col):
    while True:
        # try:
        # row = int(input("请输入你要下的行 (0, 1, 2)："))
        row = get_row
        col = get_col
        # col = int(input("请输入你要下的列 (0, 1, 2)："))
        if 0 <= row < ROWS and 0 <= col < COLS and board[row][col] == EMPTY:
            return row, col
        else:
            # print("无效的移动，请重试。")
            pass
        # except ValueError:
        #     print("请输入有效的数字（0, 1, 2）。")

# 主函数：控制游戏流程
current_player = PLAYER_X
board = [[EMPTY for _ in range(COLS)] for _ in range(ROWS)]
def main_function(get_row,get_col):
    global board
    global current_player
    # current_player = PLAYER_X  # 设置先行玩家为人类玩家

    print_board(board)


    print("玩家 X 的回合")
    row, col = get_player_move(board,get_row,get_col)
    board[row][col] = PLAYER_X
    current_player = PLAYER_O

    print("AI 的回合")
    ai_move = computer_move(board)
    print(f"AI 选择了位置：{ai_move}")  # 打印AI的移动位置
    current_player = PLAYER_X
    out_row = ai_move[0]
    out_col = ai_move[1]

    print_board(board)
    game_result = check_game_over(board)
    if game_result:
        if game_result == "Draw":
            print("平局!")
        else:
            if game_result == PLAYER_O:
                print("AI 获胜!")
            else:
                print("恭喜你获胜!")

    return out_row, out_col
